const express = require("express");
const multer = require("multer");
const auth = require("../../middleware/auth");
const upload = express.Router();

const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, "static/uploads/");
    },
    filename: function (req, file, cb) {
        const ext = file.originalname.split(".").pop();
        cb(null, Date.now() + "." + ext);
    },
});

const fileupload = multer({
    storage,
    limits: {
        fileSize: 1024 * 1024 * 2,
    },
    fileFilter: function (req, file, cb) {
        const ext = file.originalname.split(".").pop();
        if (ext !== "jpg" && ext !== "png") {
            return cb(new Error("文件格式错误"));
        }
        cb(null, true);
    },
});

// 上传文件
upload.post("/", auth, fileupload.single("avatar"), (req, res) => {
    const avatar = req.file ? `uploads/${req.file.filename}` : "";
    res.json({
        code: 200,
        msg: "上传成功",
        data: avatar,
    });
});

module.exports = upload;
